package com.ming.stringstudy.feedbacksystem.controller;

import com.ming.stringstudy.feedbacksystem.entity.Dept;
import com.ming.stringstudy.feedbacksystem.pojo.PageBean;
import com.ming.stringstudy.feedbacksystem.pojo.Result;
import com.ming.stringstudy.feedbacksystem.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author aming
 * @since 2025-01-19
 */
@RestController
@RequestMapping("/dept")
public class DeptController {
    @Autowired
    private IDeptService deptService;

    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) Integer id,
                       @RequestParam(required = false) String deptName) {
        try{
            Dept dept = new Dept();
            dept.setId(id);
            dept.setDeptName(deptName);
            PageBean pageBean = deptService.page(page, pageSize, dept);
            return Result.success(pageBean);
        }catch (Exception e){
            return Result.error("查询失败");
        }
    }


    @PostMapping
    public Result addDept(@RequestBody Dept dept) {
        try{
            int result = deptService.addDept(dept);
            if (result == 0){
                return Result.error("添加失败");
            }else {
                return Result.success("添加成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @PutMapping
    public Result updateDept(@RequestBody Dept dept) {
        try {
            int result = deptService.updateDept(dept);
            if (result == 0){
                return Result.error("修改失败");
            }else {
                return Result.success("修改成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @DeleteMapping("/{ids}")
    public Result deleteDept(@PathVariable List<Integer> ids) {
        try {
            int result = deptService.deleteDept(ids);
            if (result == 0){
                return Result.error("删除失败");
            }else {
                return Result.success("删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }
}
